package com.rongchuang.service;

import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 保存用户 token
     *
     * @param userId 用户 ID
     * @param token  token
     */
    public void saveToken(Long userId, String token) {
        redisTemplate.opsForValue().set(token, userId.toString(), 5, TimeUnit.HOURS);
    }

    /**
     * 获取用户id
     *
     * @return token
     */
    public Long getUserId(String token) {
        String userId = (String) redisTemplate.opsForValue().get(token);
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        return Long.valueOf(userId);
    }

    /**
     * 删除用户 token
     *
     * @param token
     */
    public void deleteToken(String token) {
        redisTemplate.delete(token);
    }
}
